<!-- ConfirmDialog.vue -->
<template>
  <div>
    <div class="dialog-content">
      <!-- 顶部新建按钮 -->
      <div class="add-btn">
        <el-button type="primary" size="small" @click="openFieldSelect">
          <i class="el-icon-plus"></i>新建
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="tableName" label="表" min-width="25%"></el-table-column>
        <el-table-column prop="fieldName" label="字段" min-width="60%"></el-table-column>
        <el-table-column label="操作" min-width="15%" align="center">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.$index)"
              style="color: #F56C6C;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 字段选择弹框 -->
    <div v-if="fieldSelectVisible" class=""
      v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
    <el-dialog
      title="字段选择"
      v-model="fieldSelectVisible"
      width="800px"
      append-to-body
      draggable="true"
    >
      <div class="field-select-container">
        <div class="field-select-header">
          <el-select v-model="selectedTable" placeholder="请选择表" style="width: 200px" @change="handleTableChange">
            <!-- 主表选项 -->
            <el-option
              label="主表"
              value="main"
              :disabled="isTableDisabled('main')"
            ></el-option>
            <!-- 子表选项 -->
            <el-option
              v-for="table in subTableList"
              :key="table.id"
              :label="table.label"
              :value="table.id"
              :disabled="isTableDisabled(table.id)"
            ></el-option>
          </el-select>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入关键字"
            prefix-icon="el-icon-search"
            style="width: 200px; margin-left: 10px"
          ></el-input>
        </div>

        <div class="field-select-content">
          <div class="field-list">
            <div
              class="field-item"
              v-for="field in filteredFields"
              :key="field.value"
              @click="selectField(field)"
              :class="{
                active: selectedFieldIds.includes(field.value),
                disabled: !canSelectField(getTableIdFromField(field))
              }"
            >
              <div>{{ field.label }}</div>
              <div class="field-type">{{ field.type }}</div>
            </div>
          </div>

          <div class="field-actions">
            <el-button type="text" icon="el-icon-right" @click="moveToSelected"></el-button>
            <el-button type="text" icon="el-icon-back" @click="moveFromSelected"></el-button>
          </div>

          <div class="selected-fields">
            <div
              class="field-item"
              v-for="field in selectedFields"
              :key="field.value"
              @click="selectSelectedField(field)"
              :class="{ active: selectedFieldIds.includes(field.value) }"
            >
              {{ field.label }}
            </div>
          </div>

          <div class="field-sort-actions">
            <el-button type="text" icon="el-icon-top" @click="moveUp"></el-button>
            <el-button type="text" icon="el-icon-bottom" @click="moveDown"></el-button>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button @click="fieldSelectVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmFieldSelect">确 定</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
export default {
  name: 'ConfirmDialog',
  props: {
    designer: {
      type: Object,
      required: true
    },
    formConfig: {
      type: Object,
      required: true
    },
    // 回显表格 prop
    existingUniqueData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      tableData: [], // 主表格数据
      fieldSelectVisible: false, // 字段选择弹框显示状态
      selectedTable: 'main', // 选中的表
      searchKeyword: '', // 搜索关键字
      selectedFields: [], // 已选字段列表
      selectedFieldIds: [], // 当前选中的字段id
    }
  },
  computed: {
    // 过滤后的字段列表
    filteredFields() {
      return this.currentTableFields.filter(field =>
        field.label.toLowerCase().includes(this.searchKeyword.toLowerCase()) &&
        !this.selectedFields.some(sf => sf.value === field.value)
      );
    },
    // 获取子表列表
    subTableList() {
      return this.designer.formDomainData
        .filter(widget => widget.type === 'sub-form')
        .map(widget => ({
          id: widget.id,
          label: widget.options.label || '明细表'
        }));
    },
    // 当前选中表的字段列表
    currentTableFields() {
      if (this.selectedTable === 'main') {
        // 获取主表字段
        return this.designer.formDomainData
          .filter(widget => widget.type !== 'sub-form')
          .map(widget => ({
            id: widget.id,
            value: widget.id,
            label: `[主表]${widget.options.label || ''}`,
            type: widget.type,
            options: widget.options,
          }));
      } else {
        // 获取选中子表的字段
        const subForm = this.designer.formDomainData.find(
          widget => widget.id === this.selectedTable
        );
        if (!subForm?.widgetList) return [];
        return subForm.widgetList.map(widget => ({
          id: widget.key,
          value: widget.key,
          label: `[${subForm.options.label || '明细表'}]${widget.options?.label || ''}`,
          type: widget.type,
          options: widget.options
        }));
      }
    },
  },
  watch: {
    selectedTable: {
      handler(newVal) {
        if (this.isTableDisabled(newVal)) {
          const firstSubTableField = this.selectedFields.find(field =>
            this.getTableIdFromField(field) !== 'main'
          );
          this.selectedTable = this.getTableIdFromField(firstSubTableField);
          this.$message.warning('只能选择相同子表的字段进行拼接');
          return;
        }
        console.log('切换到表:', newVal);
        this.selectedFieldIds = []; // 只清空当前选中状态
      },
      immediate: true
    },
    existingUniqueData: {
      immediate: true, // 确保组件创建时就执行
      handler(newVal) {
        if (newVal && newVal.length) {
          this.tableData = [...newVal]; // 深拷贝数据
        }
      }
    }
  },
  mounted() {
    console.log(this.formConfig)
    console.log(this.designer)
  },
  created(){
    if (this.existingUniqueData && this.existingUniqueData.length) {
      this.tableData = [...this.existingUniqueData];
    }
  },
  methods: {
    // 打开字段选择弹框
    openFieldSelect() {
      this.fieldSelectVisible = true
      // 初始化已有的唯一值数据
      if (this.existingUniqueData && this.existingUniqueData.length > 0) {
        this.tableData = [...this.existingUniqueData];
         // 通知父组件更新表格数据
        this.$emit('table-data-update', this.tableData);
      }
    },
    // 判断表是否应该被禁用
    isTableDisabled(tableId) {
      if (this.selectedFields.length === 0) return false;
      if (tableId === 'main') return false; // 主表永远可选
      // 检查已选字段中是否有子表字段
      const hasSubTableField = this.selectedFields.some(field => {
        const fieldTableId = this.getTableIdFromField(field);
        return fieldTableId !== 'main';
      });

      if (!hasSubTableField) return false; // 如果没有子表字段，所有表都可选

      // 获取已选字段中的第一个子表字段所属的表
      const firstSubTableField = this.selectedFields.find(field =>
        this.getTableIdFromField(field) !== 'main'
      );
      const firstSubTableId = this.getTableIdFromField(firstSubTableField);
      // 如果当前表是其他子表，且已经选择了不同的子表，则禁用
      return tableId !== firstSubTableId;
    },

    // 获取字段所属的表ID
    getTableIdFromField(field) {
      if (field.label.startsWith('[主表]')) return 'main';
      const subForm = this.designer.formDomainData
        .find(widget =>
          widget.type === 'sub-form' &&
          field.label.includes(`[${widget.options?.label}]`)
        );
      return subForm?.id || null;
    },

    // 当选择表变化时
    handleTableChange(value) {
      if (this.isTableDisabled(value)) {
        const firstSubTableField = this.selectedFields.find(field => 
          this.getTableIdFromField(field) !== 'main'
        );
        this.selectedTable = this.getTableIdFromField(firstSubTableField);
        this.$message.warning('只能选择相同子表的字段进行拼接');
        return;
      }
      this.selectedTable = value;
    },

    // 判断当前是否可以选择该字段
    canSelectField() {
      if (this.selectedFields.length === 0) return true;
      const lastField = this.selectedFields[this.selectedFields.length - 1];
      const isLastFieldFromMain = lastField.label.startsWith('[主表]');
      return (tableId) => {
        // 如果最后一个字段是主表字段
        if (isLastFieldFromMain) {
          // 可以选择主表字段或任意子表字段
          return true;
        }
        // 如果最后一个字段是子表字段
        const lastFieldTableId = this.getTableIdFromField(lastField);
        // 只能选择相同子表的字段
        return tableId === lastFieldTableId;
      };
    },

    // 选择字段时的处理
    selectField(field) {
      const fieldTableId = this.getTableIdFromField(field);
      // 检查是否可以选择该字段
      if (!this.canSelectField(fieldTableId)) {
        this.$message.warning('只能选择相同子表的字段进行拼接');
        return;
      }

      const index = this.selectedFieldIds.indexOf(field.value);
      if (index > -1) {
        // 取消选择
        this.selectedFieldIds.splice(index, 1);
      } else {
        // 添加选择
        this.selectedFieldIds.push(field.value);
      }
    },

    // 切换选中状态
    toggleSelectField(field) {
      const index = this.selectedFieldIds.indexOf(field.value)
      if (index > -1) {
        this.selectedFieldIds.splice(index, 1)
      } else {
        this.selectedFieldIds = [field.value]
      }
    },

   // 移动到已选区域
    moveToSelected() {
      if (this.selectedFieldIds.length === 0) return;

      const fieldsToMove = this.currentTableFields.filter(field =>
        this.selectedFieldIds.includes(field.value) &&
        !this.selectedFields.some(sf => sf.value === field.value)
      );

      // 如果已经有选中的字段，进行拼接检查
      if (this.selectedFields.length > 0) {
        const lastField = this.selectedFields[this.selectedFields.length - 1];
        const lastFieldTableId = this.getTableIdFromField(lastField);
        const allFieldsValid = fieldsToMove.every(field => {
          const fieldTableId = this.getTableIdFromField(field);
          return this.canSelectField(fieldTableId);
        });

        if (!allFieldsValid) {
          this.$message.warning('只能选择相同子表的字段进行拼接');
          return;
        }
      }

      this.selectedFields.push(...fieldsToMove);
      this.selectedFieldIds = [];
    },

     // 从已选移除
    moveFromSelected() {
      this.selectedFields = this.selectedFields.filter(
        field => !this.selectedFieldIds.includes(field.value)
      );
      this.selectedFieldIds = [];
    },

    // 选择已选字段
    selectSelectedField(field) {
      const index = this.selectedFieldIds.indexOf(field.value);
      if (index > -1) {
        this.selectedFieldIds.splice(index, 1);
      } else {
        this.selectedFieldIds = [field.value];  // 单选模式
      }
    },

    // 上移
    moveUp() {
      if (this.selectedFieldIds.length !== 1) return;
      const index = this.selectedFields.findIndex(
        field => field.value === this.selectedFieldIds[0]
      );
      if (index > 0) {
        // 交换数组元素位置
        [this.selectedFields[index - 1], this.selectedFields[index]] =
        [this.selectedFields[index], this.selectedFields[index - 1]];
      }
    },

    // 下移
    moveDown() {
      if (this.selectedFieldIds.length !== 1) return;
      const index = this.selectedFields.findIndex(
        field => field.value === this.selectedFieldIds[0]
      );
      if (index < this.selectedFields.length - 1) {
        // 交换数组元素位置
        [this.selectedFields[index], this.selectedFields[index + 1]] =
        [this.selectedFields[index + 1], this.selectedFields[index]];
      }
    },

    // 确认字段选择
    confirmFieldSelect() {
      if (this.selectedFields.length === 0) {
        this.$message.warning('请选择字段');
        return;
      }
       // 处理组合表名显示
      const getTableNames = () => {
        const tables = new Set(this.selectedFields.map(field => {
          const tableId = this.getTableIdFromField(field);
          if (tableId === 'main') {
            return '主表';
          }
          const subForm = this.designer.widgetViewList
            .find(view => view.viewTitle === this.designer.thatViewTitle)
            ?.widgetList
            .find(widget => widget.id === tableId);
          return subForm?.options?.label || '明细表';
        }));
        return Array.from(tables).join('+');
      };


      // 处理组合字段ID拼接
      const fieldIds = this.selectedFields.map(field => {
        const tableId = this.getTableIdFromField(field);
        // 如果是主表字段，直接返回字段ID
        if (tableId === 'main') {
          return field.id;
        }
        // 如果是子表字段，需要拼接子表ID
        const subForm = this.designer.widgetViewList
          .find(view => view.viewTitle === this.designer.thatViewTitle)
          ?.widgetList
          .find(widget => widget.id === tableId);
        return `${subForm.id}.${field.id}`;
      });

      // 拼接字段名称和处理字段数据
      const concatenatedField = {
        // 表名
        tableName: getTableNames(),
        fieldName: this.selectedFields.map(field => field.label).join(' + '),
        // 字段名称使用 + 号拼接
        fieldName: this.selectedFields.map(field => field.label).join(' + '),
        // 使用第一个字段的类型
        fieldType: this.selectedFields[0].type,
        // 使用所有字段ID的组合
        fieldId: fieldIds.join(','),
        // 保存所有字段的原始信息，以备后用
        fields: [...this.selectedFields],
        // 提供后端使用字段配置信息
        uniqueFields: fieldIds.join(',')
      };

      // 添加到表格数据
      this.tableData.push(concatenatedField);

      // 触发事件，将数据传递给父组件
      this.$emit('field-selected', {
        tableData: [...this.tableData],
        currentField: concatenatedField
      });
      // 触发事件，将数据传递给父组件
      this.$emit('table-data-update', this.tableData);

      // 重置弹框状态
      this.resetFieldSelectState();
    },

    // 重置字段选择状态
    resetFieldSelectState() {
      this.fieldSelectVisible = false;
      this.selectedFieldIds = [];
      this.selectedFields = [];
      this.selectedTable = 'main';
      this.searchKeyword = '';
    },

    // 删除行
    handleDelete(index) {
      this.$confirm('确认删除该字段?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        // 通知父组件更新表格数据
        this.$emit('table-data-update', this.tableData);
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.add-btn {
  margin-bottom: 15px;
}

.field-select-container {
  .field-select-header {
    margin-bottom: 20px;
  }

  .field-select-content {
    display: flex;
    justify-content: space-between;
    height: 400px;

    .field-list, .selected-fields {
      width: 320px;
      border: 1px solid #DCDFE6;
      overflow-y: auto;
      .field-item {
        padding: 8px 15px;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        &.disabled {
        opacity: 0.5;
        cursor: not-allowed;
          &:hover {
            background-color: inherit;
          }
        }
        .field-type {
          color: #909399;
          font-size: 12px;
        }
        &:hover {
          background-color: #F5F7FA;
        }
        &.active {
          background-color: #409EFF;
          color: white;
          .field-type {
            color: white;
          }
        }
      }
    }

    .field-actions, .field-sort-actions {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 0 20px;

      .el-button {
        margin: 5px 0;
      }
    }
  }
}
.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-select {
  ::v-deep .el-select-dropdown__item.is-disabled {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}
</style>